package com.leyou.page.service;

import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import java.io.File;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PageService {

    @Autowired
    private ItemClient itemClient;

    @Value("${ly.static.itemDir}")
    private String itemDir;

    @Value("${ly.static.itemTemplate}")
    private String itemTemplate;

    @Autowired
    private SpringTemplateEngine templateEngine;

    public Map<String, Object> findItem(Long spuId) {
        //根据spuId查询SpuDTO对象
        SpuDTO spuDTO = itemClient.findSpuDTOById(spuId);
        //根据分类id集合获取分类对象集合
        List<Category> categories = itemClient.findCategoriesByIds(spuDTO.getCategoryIds());
        //根据品牌id查询品牌对象
        Brand brand = itemClient.findBrandById(spuDTO.getBrandId());
        //根据分类id查询规格组集合
        List<SpecGroupDTO> groupDTOList = itemClient.findSpecGroupWithParams(spuDTO.getCid3());
        Map<String, Object> itemInfo = new HashMap<>();
        itemInfo.put("categories", categories);
        itemInfo.put("brand", brand);
        itemInfo.put("spuName", spuDTO.getName());
        itemInfo.put("subTitle", spuDTO.getSubTitle());
        itemInfo.put("detail", spuDTO.getSpuDetail());
        itemInfo.put("skus", spuDTO.getSkus());
        itemInfo.put("specs", groupDTOList);
        return itemInfo;
    }

    /**
     * 生成静态页
     */
    public void buildStaticPage(Long spuId){
        //提供上下文对象
        Context context = new Context();
        context.setVariables(findItem(spuId));
        //创建静态资源服务器文件对象
        File targetFile = new File(itemDir);
        //指定静态页面的名称
        String fileName = spuId+".html";
        //创建商品静态页文件对象
        File itemPageFile = new File(targetFile, fileName);
        //创建一个打印流
        try(PrintWriter write = new PrintWriter(itemPageFile);) {
            //生成静态页
            templateEngine.process(itemTemplate, context, write);
        }catch (Exception e){
            throw new LyException(ExceptionEnum.FILE_WRITER_ERROR);
        }
    }

    public void delPage(Long id) {
        //先获取要删除的静态页文件
        //创建静态资源服务器文件对象
        File targetFile = new File(itemDir);
        //指定静态页面的名称
        String fileName = id+".html";
        //创建商品静态页文件对象
        File itemPageFile = new File(targetFile, fileName);
        //如果存在则删除
        if(itemPageFile.exists()){
            itemPageFile.delete();
        }
    }
}
